<script setup lang="js">
import {ref, onMounted, computed, watch} from "vue";
import {useRouter} from "vue-router";
import {InfoFilled, Search, Tickets} from "@element-plus/icons-vue";
import {fetchOrderList, closeOrder, deleteOrder} from "@/api/orderList.js";
import {ElMessage} from "element-plus";
import LogisticsDialog from "./components/logisticsDialog.vue";
import CloseDialog from "./components/closeDialog.vue";


onMounted(() => {
  getOrderList()
})
// 格式化订单创建时间
const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
// 格式化订单支付方式
const formatPayType = (payType) => {
  switch (payType) {
    case 1:
      return '支付宝'
    case 2:
      return '微信'
    default:
      return '未支付'
  }
}
// 格式化订单状态
const formatStatus = (value) => {
  switch (value) {
    case 1:
      return '待发货'
    case 2:
      return '已发货'
    case 3:
      return '已完成'
    case 4:
      return '已关闭'
    case 5:
      return '无效订单'
    default:
      return '待付款'
  }
}
const router = useRouter()
const orderList = ref([])
const total = ref(0)
const getOrderList = async () => {
  const res = await fetchOrderList(listQuery)
  orderList.value = res.data.data.list
  total.value = res.data.data.total
}

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  orderSn: null,
  receiverKeyword: null,
  status: null,
  orderType: null,
  sourceType: null,
  createTime: null,
};
const listQuery = Object.assign({}, defaultListQuery)
const orderSearch = ref({
  orderSn: null,
  receiverKeyword: null,
  status: null,
  orderType: null,
  sourceType: null,
  createTime: null,
})
const statusOptions = [
  {label: '待付款', value: 0},
  {label: '待发货', value: 1},
  {label: '已发货', value: 2},
  {label: '已完成', value: 3},
  {label: '已关闭', value: 4}
]
const orderTypeOptions = [
  {label: '正常订单', value: 0},
  {label: '秒杀订单', value: 1},
]
const sourceTypeOptions = [
  {label: 'PC订单', value: 0},
  {label: 'App订单', value: 1},
]
const operateOptions = [
  {label: '批量发货', value: 1},
  {label: '关闭订单', value: 2},
  {label: '删除订单', value: 3},
]
const operateType = ref('')
const multipleSelection = ref([])

// 订单列表选择变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 查询条件重置
const handleResetSearch = () => {
  listQuery.pageNum = 1
  listQuery.orderSn = null
  listQuery.receiverKeyword = null
  listQuery.status = null
  listQuery.orderType = null
  listQuery.sourceType = null
  listQuery.createTime = null
  orderSearch.value = Object.assign({}, defaultListQuery)
  getOrderList()
}

// 查询条件提交
const handleSearch = () => {
  listQuery.pageNum = 1
  listQuery.orderSn = orderSearch.value.orderSn
  listQuery.receiverKeyword = orderSearch.value.receiverKeyword
  listQuery.status = orderSearch.value.status
  listQuery.orderType = orderSearch.value.orderType
  listQuery.sourceType = orderSearch.value.sourceType
  listQuery.createTime = orderSearch.value.createTime
  getOrderList()
}

// 批量操作类型
const handleBatchOperate = () => {

}
// TODO: 订单详情
const handleViewOrder = (row) => {
  router.push({path: '/detail/order', query: {id: row.id}})
}

// TODO: 关闭订单
const closeOrderText = ref({
  dialogVisible:false,
  content:null,
  orderIds:[]
})
const handleCloseOrder = (row) => {
  closeOrderText.value.dialogVisible = true
  closeOrderText.value.orderIds = [row.id]
}
const closeContent = () => {
  closeOrderText.value.dialogVisible = false
  getOrderList()
}

// TODO: 发货订单
const handleDeliveryOrder = (row) => {
  // let listItem = covertOrder(row)
  router.push({path: '/deliverList/order', query:{id:row.id}})
}
const covertOrder = (order) => {
  let address=order.receiverProvince+order.receiverCity+order.receiverRegion+order.receiverDetailAddress;
  let listItem = {
    orderId:order.id,
    orderSn:order.orderSn,
    receiverName:order.receiverName,
    receiverPhone:order.receiverPhone,
    receiverPostCode:order.receiverPostCode,
    address:address,
    deliveryCompany:null,
    deliverySn:null
  }
  return listItem
}

// TODO: 订单跟踪
const logisticsDialogVisible = ref(false)
const handleViewLogistics = (row) => {
  logisticsDialogVisible.value = true
}

// TODO: 删除订单
const handleDeleteOrder = (row) => {
  let ids = [];
  ids.push(row.id);
  let params = new URLSearchParams()
  params.append('ids', row.id)
  deleteOrder(params).then(res => {
    ElMessage.warning(res.data.message)
    ElMessage.success('订单删除成功')
    getOrderList()
  }).catch(err => {
    ElMessage.error(err)
  })
}

// TODO: 分页操作方法
const handleSizeChange = (size) => {
  listQuery.pageSize = size;
  getOrderList()
}
const handleCurrentChange = (val) => {
  listQuery.pageNum = val;
  getOrderList()
}
</script>

<template>
  <div class="order-list">
    <!-- 顶部搜索区域-->
    <div class="top-bar">
      <div class="logo">
        <div class="logo-text">
          <el-icon>
            <Search/>
          </el-icon>
          <span>筛选搜索</span>
        </div>
        <div class="search-btn">
          <el-button icon="search" type="primary" @click="handleSearch()">查询结果</el-button>
          <el-button icon="refresh" @click="handleResetSearch()">重置</el-button>
        </div>
      </div>
      <div class="search">
        <el-form :inline="true" v-model="orderSearch" label-width="100px">
          <el-form-item label="输入搜索：">
            <el-input v-model="orderSearch.orderSn" class="input-width" placeholder="订单编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="收货人：">
            <el-input v-model="orderSearch.receiverKeyword" class="input-width"
                      placeholder="收货人姓名/手机号码" clearable></el-input>
          </el-form-item>
          <el-form-item label="提交时间：">
            <el-date-picker
                v-model="orderSearch.createTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="MMM DD, YYYY"
                time-format="HH:mm"
                placeholder="请选择时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="订单状态：">
            <el-select v-model="orderSearch.status" class="input-width" placeholder="请选择" clearable>
              <el-option v-for="item in statusOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单分类：">
            <el-select v-model="orderSearch.orderType" class="input-width" placeholder="请选择" clearable>
              <el-option v-for="item in orderTypeOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单来源：">
            <el-select v-model="orderSearch.sourceType" class="input-width" placeholder="请选择" clearable>
              <el-option v-for="item in sourceTypeOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 中部添加按钮 -->
    <div class="center-bar">
      <div class="add-btn">
        <el-icon style="font-size: 20px;">
          <Tickets/>
        </el-icon>
        <span>数据列表</span>
      </div>
    </div>
    <!-- 底部列表区域 -->
    <div class="bottom-bar">
      <el-table :data="orderList" style="width: 100%;" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="100" align="center"></el-table-column>
        <el-table-column label="订单ID" width="150" align="center">
          <template #default="{row}">{{ row.id }}</template>
        </el-table-column>
        <el-table-column label="订单编号" width="" align="center">
          <template #default="{row}">{{ row.orderSn }}</template>
        </el-table-column>
        <el-table-column label="提交时间" width="" align="center">
          <template #default="{row}">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="用户账号" width="200" align="center">
          <template #default="{row}">
            {{ row.memberUsername }}
          </template>
        </el-table-column>
        <el-table-column label="订单金额" width="200" align="center">
          <template #default="{row}">
            ￥{{ row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column label="支付方式" align="center">
          <template #default="{row}">
            {{ formatPayType(row.payType) }}
          </template>
        </el-table-column>
        <el-table-column label="订单来源" align="center">
          <template #default="{row}">
            {{ row.sourceType === 1 ? 'App订单' : 'PC订单' }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center">
          <template #default="{row}">
            {{ formatStatus(row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button style="border:1px solid #26a2de;color: #26a2de;" @click="handleViewOrder(row)">查看订单
            </el-button>
            <el-button type="warning" @click="handleCloseOrder(row)" v-show="row.status===0">关闭订单</el-button>
            <el-button type="primary" @click="handleDeliveryOrder(row)" v-show="row.status===1">订单发货</el-button>
            <el-button type="success" @click="handleViewLogistics(row)" v-show="row.status===2||row.status===3">订单跟踪</el-button>
            <el-popconfirm
                width="220"
                placement="bottom"
                :icon="InfoFilled"
                icon-color="#626AEF"
                confirm-button-text="确定"
                cancel-button-text="取消"
                title="是否确定删除该订单？"
                @confirm="() => handleDeleteOrder(row)"
            >
              <template #reference>
                <el-button type="danger" v-show="row.status===4">删除订单</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部分页 -->
    <div class="page-bar">
      <div class="select-type">
        <span>批量操作：</span>
        <el-select v-model="operateType" placeholder="请选择操作">
          <el-option
              v-for="item in operateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-button
            style="margin-left: 20px"
            class="search-button"
            @click="handleBatchOperate()"
            type="primary"
            size="small">
          确定
        </el-button>
      </div>
      <el-pagination
          background
          layout="total, sizes,prev, pager, next,jumper"
          :total="total"
          :page-sizes="[5,10,15,20]"
          v-model:page-size="listQuery.pageSize"
          v-model:current-page="listQuery.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>

  <!--  订单跟踪弹窗-->
  <logistics-dialog v-model="logisticsDialogVisible"/>
  <!--  关闭订单弹窗-->
  <close-dialog v-model="closeOrderText.dialogVisible"
                @close="closeContent"
                :closeOrderText="closeOrderText"/>

</template>

<style scoped lang="scss">
.order-list {
  height: 100%;
  display: flex;
  flex-direction: column;

  .top-bar {
    //height: 100px;
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;

    .logo {
      width: 100%;
      font-size: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        margin: 0 8px;
      }

      .search-btn {
        padding: 0 10px;
      }
    }

    .search {
      width: 100%;

      .el-form {
        margin-top: 20px;

        .el-form-item {
          width: 280px;
        }
      }
    }
  }

  .center-bar {
    //height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;

    .add-btn {
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
        font-size: 18px;
      }
    }
  }

  .bottom-bar {
    //border: 1px solid #d5d5d5;

    .operation-btns {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      p {
        width: 100%;
        margin: 8px 0;
      }
    }
  }

  .page-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;
    padding: 10px 20px;
    border: 1px solid #d5d5d5;

    .select-type {
      width: 400px;
      display: flex;
      align-items: center;
      justify-content: space-between;

    }

    span {
      width: 150px;
    }
  }

}
</style>